﻿using Microsoft.SqlServer.Dts.Runtime;
using System;
using System.Windows.Forms;

namespace MySSISComponents
{
    [DtsTask
    (
        DisplayName = "MyMsgBox",
        Description = "Use to Popup a window to show message"
    )
    ]
  public  class MyMsgBox:Task
    {
        public string ReadOnlyVariables { set; get; }

     
        public override DTSExecResult Validate(Connections         connections,
                                               VariableDispenser   variableDispenser,
                                               IDTSComponentEvents componentEvents,
                                               IDTSLogging log)

        {
            DTSExecResult execResult = base.Validate(connections,variableDispenser, componentEvents, log);
            //check the ReadOnlyVariables
            if (string.IsNullOrEmpty(ReadOnlyVariables))
            {
                componentEvents.FireError(0, "",
                    string.Format("You must specify at least a variable name", ReadOnlyVariables), "", -1);
                return DTSExecResult.Failure;
            }

            foreach (var v in ReadOnlyVariables.Split(';'))
            {
                if (!variableDispenser.Contains(v))
                {
                    componentEvents.FireError(0, "",
                        string.Format("The specified variable '{0}' does not exist", v), "", -1);
                    return DTSExecResult.Failure;
                }
            }
            return execResult;
        }


        public override DTSExecResult Execute(Connections connections,
         VariableDispenser variableDispenser, IDTSComponentEvents
         componentEvents, IDTSLogging log, object transaction)
        {
            try
            {
                //Read all variables and pop up out
                //ReadOnlyVariables
                string[] strvars = ReadOnlyVariables.Split(';');
                Variables vars = null;
                string msg = string.Empty;
                foreach (var v in strvars)
                {
                    variableDispenser.LockForRead(v);
                }
                variableDispenser.GetVariables(ref vars);
                foreach (var v in vars)
                {
                    msg += v.Namespace + "::" + v.Name + ":";
                    msg += v.Value.ToString() + Environment.NewLine;
                }

                MessageBox.Show(msg);
                return DTSExecResult.Success;
            }
            catch (Exception ex)
            {
                componentEvents.FireError(0, "MessageBoxTask Exception",ex.Message, "", 0);
                return DTSExecResult.Failure;
            }
        }
    }

}

